﻿using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using Flatland.GeneticProgramming.CoreTypes;

namespace Flatland.GeneticProgramming.FileWriter {
    /// <summary>
    /// Writes a genotype file from a Report
    /// </summary>
    public class GeneFileWriter {
        /// <summary>
        /// Serializes a report to a file.
        /// </summary>
        /// <param name="report"></param>
        /// <param name="folder"></param>
        /// <returns>File path</returns>
        public string Serialize(Report report, string folder = null) {
            string geneFilename = report.GenoType.GetType().Name;
            string dir = Program.MY_GENES_FOLDER;
            if (!string.IsNullOrEmpty(folder)) {
                dir = folder;
            }
            dir = Directory.GetCurrentDirectory() + "\\" + dir;
            var d = Directory.CreateDirectory(dir);
            d.Attributes &= ~FileAttributes.ReadOnly;
            int count = 0;
            foreach (var entry in Directory.GetFileSystemEntries(dir)) {
                if (entry.Contains(geneFilename))
                    count++;
            }
            if (count != 0)
                geneFilename += count;
            IFormatter formatter = new BinaryFormatter();
            string filePath = dir + "\\" + geneFilename + Program.GENE_FILE_EXTENSION;
            Stream stream = new FileStream(filePath, FileMode.Create,
                                           FileAccess.Read | FileAccess.Write, FileShare.ReadWrite);
            formatter.Serialize(stream, report);
            stream.Close();
            return filePath;
        }
    }
}
